<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>2_react生命周期(旧)</title>
  <!-- 引入React核心库 -->
  <script type="text/javascript" src="../js/17.0.2/react.development.js"></script>
  <!-- 引入react-dom,用于支持react操作DOM -->
  <script type="text/javascript" src="../js/17.0.2/react-dom.development.js"></script>
  <!-- 引入babel，用于把jsx转为js -->
  <script type="text/javascript" src="../js/babel.min.js"></script>
  <style>
    .news {
      width: 100px;
      height: 100px;
      overflow: auto;
      background: greenyellow;
    }

    .news news-item {
      width: 100%;
      height: 30px;
      padding: 0 10px;
      line-height: 30px;
    }
  </style>
</head>

<body>
  <!-- <div id="test1"></div> -->
  <div id="test2"></div>

  <script type="text/babel">
    class NewsList extends React.Component {
      state = {
        newsList: []
      }
      componentDidMount () {
        const { newsList } = this.state

        setInterval(() => {
          newsList.unshift(`新闻${newsList.length + 1}`)
          this.setState({ newsList: newsList })
        }, 1000)
      }
      // 获取快照，用于getSnapshotBeforeUpdate
      getSnapshotBeforeUpdate () {
        return this.refs.list.scrollHeight
      }

      // 更新前，用于滚动条回弹
      componentDidUpdate (prevProps, prevState, snapshot) {
        this.refs.list.scrollTop += this.refs.list.scrollHeight - snapshot
      }
      render () {
        return (
          <div className="news" ref='list'>
            {
              this.state.newsList.map((item, index) => {
                return (
                  <div className="news-item" key={index}>{item}</div>
                )
              })
            }
          </div>
        )
      }
    }
    ReactDOM.render(<NewsList />, document.getElementById('test2'))
  </script>
</body>

</html>